<template>
  <div class="yunqi">
    <!--<mt-header fixed title="小普智能">-->
      <!--<router-link to="/" slot="left">-->
        <!--<mt-button icon="back">返回</mt-button>-->
      <!--</router-link>-->
      <!--<mt-button icon="more" slot="right"></mt-button>-->
    <!--</mt-header>-->
    <div style="margin-top: 5rem">
      <span>添加小普马桶盖</span>
    </div>
    <div style="width: 60%;margin:2rem auto 0 auto">
      <img style="width: 100%" src="../../../../static/img/addto.png" />
    </div>
    <div style="margin: auto">
      <span style="font-size: 0.5rem;">连接电源开机即可连接</span>
    </div>
    <Loading v-if="showLoading" ></Loading>
    <Process v-if="showLoading" :alertText="alertText" ></Process>
    <addtoAlert v-if="showAddtoAlert"></addtoAlert>
    <IsReg v-if="IsRegStatus"></IsReg>
    <!--<Inputk-->
      <!--v-if="showAlert"-->
      <!--:showHide="showAlert"-->
      <!--@closeTip="closeTip"-->
      <!--@goToDo="goToDo"-->
      <!--:alertText="alertText"-->
      <!--:LeftText="LeftText"-->
      <!--:RightText="RightText"-->
    <!--&gt;-->
    <!--</Inputk>-->
  </div>
</template>

<script>
  import {mapMutations,mapState} from 'vuex'
  import Loading from '@/components/common/Loading'
  import Process from '@/components/common/Process'
  import Inputk from '@/components/common/Inputk'
  import addtoAlert from '@/components/common/addtoAlert'

  import {Register} from '../../../store/_CRC'
  import IsReg from "../../common/IsReg";

  export default {
    name: 'AddTo',
    data () {
      return {
        IsRegStatus:false,
        IsConnectAddto:false,
        availableChange:false,
        IsreJ:false,
        exitTime:0,
        showAddtoAlert:false,
        OSTypeSet:false,
        showLoading:true,
        alertText:'正在努力注册设备，请稍后',
        LeftText: '',
        RightText: '',
        showAlert: true,
        BANBEN: '',
        deviceId: '',
        YinJBANBEN: 'HC-08'
      }
    },
    components: {
      IsReg,
      addtoAlert,
      Loading,
      Process,
      Inputk
    },
    computed:{
      ...mapState([
        // 'getF03String'
        'deviceIdConnect'
      ])
    },
    watch: {
    },
    methods: {
      ...mapMutations([
        'setConnectDeviceId'
        // 'getF03StringConnect'
      ]),
      tolcallback () {
        var self = this
        window.getStorageSync = function (key) {
          if (self.OSTypeSet==false) {
            var serviceId = "0000ffe0-0000-1000-8000-00805f9b34fb"
            var characteristicId = "0000ffe1-0000-1000-8000-00805f9b34fb"
          } else if(self.OSTypeSet==true){
            var serviceId = "ffe0"
            var characteristicId = "ffe1"
          }
          switch (key) {
            case 'deviceId':
              // return state.Duuid
              // return "C8:FD:19:58:BC:10"
            // return "3C:A3:08:A9:E3:10";
              return self.deviceId
            case 'serviceId':
              return serviceId
            case 'characteristicId':
              return characteristicId
          }
        }
        window.setNotifyIOS = function ()
        {
          var deviceId = window.getStorageSync('deviceId');
          var serviceId = window.getStorageSync('serviceId');
          var characteristicId = window.getStorageSync('characteristicId');
          sleep(1000)
          var re = window.hilink.notifyBLECharacteristicValueChange(deviceId,serviceId,characteristicId,true);
          if(re==0) {
            console.log('执行成功:1ttt1');
            setTimeout('getBenTowrite()',1000)
            return true;
          } else {
            console.log('执行失敗:11');
          }

        }
        window.setNotify = function ()
        {
          var deviceId = window.getStorageSync('deviceId');
          var serviceId = window.getStorageSync('serviceId');
          var characteristicId = window.getStorageSync('characteristicId');
          var re = window.hilink.notifyBLECharacteristicValueChange(deviceId,serviceId,characteristicId,true);
          if(re==0) {
            setTimeout('getBenTowrite()',1000)
            console.log('执行成功:1ttt1');
            return true;
          } else {
            setTimeout('window.setNotify()',1000)
            console.log('执行失敗:111222');
          }

        }
        window.getBenTowrite = function () {
          var deviceId = window.getStorageSync('deviceId');
          var serviceId = window.getStorageSync('serviceId');
          var characteristicId = window.getStorageSync('characteristicId');
          var wrTore = Register.getF03String(1, 78, 1)
          var data = window.writeTo16(wrTore)
          console.log(wrTore)
          var err = window.hilink.writeBLECharacteristicValue(deviceId, serviceId, characteristicId, data,"writeCallback")
        }
        window.writeCallback = function (re) {
          console.log('写入成功'+re)
        }
        window.writeTo16 = function (dataArr) {
          var newstr = '';
          for(var i = 0;i< dataArr.length;i++) {
            var str16 = (Array(2).join(0) + dataArr[i].toString(16)).slice(-2);
            newstr += str16
          }
          return newstr
        }
          window.readTo10 = function (dataStr) {
          var newArr = new Array
          for(var i = 0; i<dataStr.length;i=i+2) {
            newArr.push(parseInt(dataStr.substring(i,i+2),16))
          }
          return newArr
        }
          window.ValueChange = function (re)
          {
            console.log(re)
            console.log('gaga666')
            var valueC = eval("("+re+")")
            var data = valueC.data
            var dataArr = window.readTo10(data)
            var zhuBANBEN = (dataArr[4] & 0x00f0) >> 4
            var fuBANBEN = (dataArr[4] & 0x000f)/10
            self.BANBEN = zhuBANBEN + fuBANBEN
            // self.deviceId = "3C:A3:08:A9:E3:10"
            if(self.OSTypeSet==true) {
              window.hilink.readBLECharacteristicValue(self.deviceId, "180A", "2A23", 'readBLECallBack')
            } else {
              console.log('555')
              if(self.IsreJ === false) {
                console.log(self.BANBEN)
                self.IsreJ = true
                console.log(self.deviceId)
                if(self.showAddtoAlert==false) {
                  window.hilink.registerBleDevice(self.deviceId,self.BANBEN,self.YinJBANBEN,'callBackRegisterBleDevice')
                }
                console.log(self.YinJBANBEN)
              }

            }

          }
         window.connetState = function (re)
         {
           var data = eval("("+re+")")
           if(data.connected==true) {
             console.log('连接状态:'+data.connected)
             window.hilink.onBLECharacteristicValueChange ("ValueChange")

             if(self.OSTypeSet==true) {
               // window.hilink.getBLEDeviceCharacteristics(self.deviceId,'ffe0','setNotifyIOS')
             } else {
               self.IsConnectAddto = true
               self.showAddtoAlert = false
               setTimeout("window.setNotify()", 1000)
             }
           } else {
              console.log('连接失败aaaaaaaa')
              window.hilink.createBLEConnection(self.deviceId)
             self.IsConnectAddto = false

              var numberMillis = 20000
              var now = new Date()
              self.exitTime = now.getTime() + numberMillis
              clearInterval(window.ADDTOOut)
              window.ADDTOOut = setInterval("window.eqTime()",1000)
           }
         }
          window.eqTime = function(){
            var now = new Date()
              if (now.getTime() > self.exitTime){
                console.log('aagag')
                self.showAddtoAlert = true
                clearInterval(window.ADDTOOut)
              }
          }

      }
    },
    mounted () {
      var self = this
      window.checkConnect = function(){
        if(self.IsConnectAddto==false) {
          self.showAddtoAlert = true
        }
      }
      window.SetTimeOUTc = setTimeout("checkConnect()",30000)

      this.tolcallback();
      window.sleep = function(numberMillis) {
        var now = new Date();
        var exitTime = now.getTime() + numberMillis;
        while (true) {
          now = new Date();
          if (now.getTime() > exitTime)
            return;
        }
      }
      // window.writeCallback = function (re) {
      //   console.log('写入成功'+re)
      // }
      window.callBackRegisterBleDevice = function(recode) {
        var data = eval("("+recode+")")
        console.log(data)
        if(data.errCode==0) {
          console.log('注册成功:'+recode)
        } else if(data.errCode==90012) {
          console.log('重复注册:'+recode)
          self.IsRegStatus = true
        }
      }
      window.readBLECallBack = function(re){
        var valueC = eval("("+re+")")

        var a=valueC.data
        var str6 = a.substr(a.length-6)
        var strr6 = a.substr(0,6)
        var str = str6[4]+str6[5]+":" + str6[2]+str6[3]+":"+str6[0]+str6[1]+":"+strr6[4]+strr6[5]+":"+strr6[2]+strr6[3]+":"+strr6[0]+strr6[1]
        console.log("readBLECallBack:"+self.IsreJ)
        // if(self.IsreJ===false) {
        //   self.IsreJ = true
          console.log(self.BANBEN)
          console.log(self.YinJBANBEN)
          console.log("registerBleDevice:"+self.showAddtoAlert)
        if(self.BANBEN===0){
          return
        }
            if(self.showAddtoAlert==false) {
              window.hilink.registerBleDevice(str, self.BANBEN, self.YinJBANBEN, 'callBackRegisterBleDevice')
            }
        // }
      }
      window.getCurrentUnregisteredDevice = function (re) {
        var valueC = eval("("+re+")")
        self.deviceId = valueC.deviceId
        if(self.OSTypeSet==true) {
          window.hilink.getBLEDeviceCharacteristics(self.deviceId,'ffe0','setNotifyIOS')
        }
        window.hilink.createBLEConnection(self.deviceId)
      }
      window.getSystemInfoSyncCallBack = function (re) {
        var info = eval("("+re+")")
        if(info.platform=='iOS'){
          self.OSTypeSet = true
        } else {
          self.OSTypeSet = false
        }
        if(self.OSTypeSet==true) {
          // sleep(1000)
        }
        window.hilink.getCurrentUnregisteredDevice("getCurrentUnregisteredDevice")
      }

      window.onBluetoothAdapterStateChangeCallback = function(resultStr) {
        console.log(resultStr);
        var data = eval("("+resultStr+")")
        if(data.available==true){
          if(self.availableChange == false){
            if(self.deviceId === ''){
              console.log('重新连接555');
              window.hilink.onBLEConnectionStateChange ("connetState")
              window.hilink.getSystemInfoSync('getSystemInfoSyncCallBack')
            } else {
              console.log('重新连接666');
              window.hilink.onBLEConnectionStateChange ("connetState")
              window.hilink.getSystemInfoSync('getSystemInfoSyncCallBack')
            }
          }
          if(self.availableChange==false) {
            self.availableChange = true
          }
        } else{
          // window.hilink.openBluetoothAdapter()
        }
      }

      // window.hilink.onBluetoothAdapterStateChange('onBluetoothAdapterStateChangeCallback');
      // window.hilink.openBluetoothAdapter()
      window.hilink.onBluetoothAdapterStateChange('onBluetoothAdapterStateChangeCallback');
      var openErr = window.hilink.openBluetoothAdapter()
      console.log(openErr)

      if(self.availableChange==false){
        window.hilink.onBLEConnectionStateChange ("connetState")
        window.hilink.getSystemInfoSync('getSystemInfoSyncCallBack')
      }
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.yunqi{
  text-align: center;
}
</style>
